package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xiao-hong-shu-app/cache"
	"xiao-hong-shu-app/model"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	title := c.PostForm("title")
	if name == "" || title == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}

	article := model.Article{
		Name:  name,
		Title: title,
	}
	err := model.DB.Create(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "article_" + strconv.Itoa(int(article.ID))
	var articles *model.Article
	model.DB.Where("id=?", article.ID).Find(&articles)
	jsonData, _ := json.Marshal(articles)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := model.DB.Where("id=?", id).Delete(&model.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "Del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func List(c *gin.Context) {
	var article []*model.Article
	model.DB.Find(&article)
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData != "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
